package com.iot.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.commonutils.utils.Result;
import com.iot.user.entity.User;
import com.iot.user.entity.UserRole;
import com.iot.user.mapper.UserMapper;
import com.iot.user.mapper.UserRoleMapper;
import com.iot.user.service.UserRegisteredService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserRegisteredServiceImpl extends ServiceImpl<UserMapper, User> implements UserRegisteredService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public Result registered(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> name = queryWrapper.eq("name", user.getName());
        List<User> listUser = list(name);
        if (listUser != null && listUser.size() == 1) {

            return Result.error("用户名已经存在,请重新输入");
        }
        user.setCreatedTime(new Date());
        user.setLoginTime(new Date());
        user.setSalt(user.getName());
        user.setStatus(9);
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((user.getPassword() + user.getSalt()).getBytes());
        user.setPassword(md5DigestAsHex);
        //保存用户
        save(user);
        //给注册用户加权限
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        QueryWrapper<User> name1 = queryWrapper1.eq("name", user.getName());
        List<User> listUser1 = list(name1);
        User user1 = listUser1.get(0);
        UserRole userRole = new UserRole();
        userRole.setUserId(user1.getId());
        userRole.setRoleId("2");
        userRoleMapper.insert(userRole);
        return Result.success("用户保存成功!");
    }
}
